// @ts-nocheck
import { useWsStore } from "@/stores/ws";

let heart: ReturnType<typeof setInterval> | null = null;
let repeatKey = "";
let repeatNum = 1;
let callBakFn: (() => void) | null = null;

declare const uni: any;

function initWS(callbak: (() => void) | null = null): void {
    if (callbak != null) {
        callBakFn = callbak;
    }
    const WsStore = useWsStore();
    console.log("zoule-11");
    // 如果当前是链接的状态 直接返回 
    if (WsStore.socketFlag) {
        console.log("zoule-14");
        return;
    }
    // 链接ws服务器
    uni.connectSocket({
        url: import.meta.env.VITE_WSAPI_URL
    });

    uni.onSocketOpen((res: any) => {
        // 执行回调
        if (callBakFn != null) {
            callBakFn();
        }
        log("链接创建成功！");
        // 恢复链接次数
        repeatNum = 1;
        // 更改链接状态
        WsStore.setSocketFlag(true);

        // 心跳检测 通过定时器 定时像服务端推送消息
        heart = setInterval(() => {
            if (!WsStore.heartFlag) {
                sendSocketMessage({
                    type: 'ping'
                });
                WsStore.setHeartFlag(true);
            } else {
                clearInterval(heart!);
                heart = null;
                WsStore.setSocketFlag(false);
                // 调用重连的方法 
            }
        }, 3000);
        // sendSocketMessage({
        //     uid: userInfo.value.id,
        //     type: 'friendList'
        // })
    });
    // 服务端给我推送的消息
    uni.onSocketMessage((res: any) => {
        // console.log('收到服务器内容：' + res.data);
        // 将获取到的内容转换成json
        let data: any = null;
        try {
            data = JSON.parse(res.data);
        } catch (err) {
            data = {
                type: 'error',
                data: res.data
            };
        }

        // type=pong 代表服务端状态回填
        if (data.type === 'pong') {
            WsStore.setHeartFlag(false);
        } else if (data.type === 'friendList') {
            console.log(data.data.list, 70);
            // messageList.value = data.data.list
            WsStore.setResource('friendList', data.data.list);
        } else if (data.type === 'ai') {
            WsStore.setResource('ai', {
                id: new Date().getTime(),
                avatar: 'https://cdn8.axureshop.com/demo2024/2251242/images/%E7%A7%81%E4%BF%A1%E8%AF%A6%E6%83%85/u2461.svg', // 对方的头像
                text: data.data.content,
                isMine: false
            }, 'append');
        }
    });

    uni.onSocketError(() => {
        logErr("链接异常");
    });

    uni.onSocketClose(async () => {
        logErr("链接关闭");
        // 在这里面进行重连
        WsStore.setSocketFlag(false);
        WsStore.setHeartFlag(false);
        // 重连次数
        if (repeatNum > import.meta.env.VITE_SOCKET_NUM) {
            logErr("已经超过重连次数，不在进行重连");
        } else {
            log(`尝试重连(${repeatNum})...`);
            await wait(3);
            initWS();
        }
        repeatNum++;
    });
}

function wait(s: number): Promise<void> {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve();
        }, s * 1000);
    });
}

function sendSocketMessage(data: any): void {
    // console.log(data, '62')
    uni.sendSocketMessage({
        data: JSON.stringify(data)
    });
}

function log(text: string): void {
    console.log(`%c${text}`, 'color: green; font-weight: bold;');
}

function logErr(text: string): void {
    console.log(`%c${text}`, 'color: red; font-weight: bold;');
}

export {
    initWS,
    sendSocketMessage
}